<template>
	<view class="applyAdministrators">
		<view class="applyAdministrators-content ff-bg-fff ff-color-222 ff-font-14 ff-margin-12 ff-border-radius-10">
			<view
				class="ff-font-weight-600 ff-color-222 ff-padding-left-15 ff-padding-top-15 ff-font-15 ff-margin-bottom-5">
				申请成为管理员</view>
			<view class="ff-flex-between ff-align-items-one ff-padding-15 ff-border-bottom">
				<view class="applyAdministrators-content-title">姓名</view>
				<input class="ff-text-right ff-color-222" v-model.trim="params.name" placeholder="请输入" type="text" />
			</view>
			<view class="ff-flex-between ff-align-items-one ff-padding-15 ff-border-bottom">
				<view class="applyAdministrators-content-title">身份证号</view>
				<input style="width: 400rpx;" class="ff-text-right ff-color-222" maxlength="18"
					v-model.trim="params.idcard" placeholder="请输入" type="idcard" />
			</view>
			<view class="ff-flex-between ff-align-items-one ff-padding-15 ff-border-bottom">
				<view class="applyAdministrators-content-title">身份认证</view>
				<view class="ff-text-right">
					<view @click="faceAuthenticationClick" v-if="!faceInfo.faceState" class="ff-color-blue">人脸认证</view>
					<view v-else class="ff-color-999">认证成功</view>
				</view>
			</view>
			<view class="ff-flex-between ff-align-items-one ff-padding-15 ff-border-bottom">
				<view class="applyAdministrators-content-title">现任管理员手机号</view>
				<input class="ff-text-right ff-color-D3" :disabled="true" v-model.trim="params.administratorsphone"
					placeholder="请输入" type="number" />
			</view>
			<view class="ff-flex-between ff-align-items-one ff-padding-15 ff-border-bottom">
				<view class="applyAdministrators-content-title">授权码</view>
				<view class="ff-align-items-one">
					<input class="ff-text-center ff-color-222" maxlength="10" v-model.trim="params.code"
						placeholder="请输入" type="number" />
					<view class="ff-margin-left-20">
						<view v-if="validCodeList.disableValidCode" @click.stop="getValidCoded" class="ff-color-blue">
							{{ validCodeList.validCodeText }}
						</view>
						<view v-else class="ff-color-cancel">{{ validCodeList.validTimeText }}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="tips ff-font-12 ff-color-999" @click="tipsClick"><u-icon name="question-circle" color="red"
				size="36"></u-icon></view>
		<view class="ff-flex-between">
			<view class="applyAdministrators-but"><u-button type="primary" shape="circle"
					@click="applyClick">确认申请</u-button></view>
		</view>
		<f-loading ref="loading" />
		<u-toast ref="uToast" />
		<u-modal :title="failTitle" v-model="failModal" :content-style="{ 'line-height': '1.5' }"
			:content="failContent" />
		<!-- 认证失败弹框 -->
		<u-modal title="申请成为新管理员方法" confirm-text="我知道了" v-model="tipsModal" :content-style="{ 'line-height': '1.5' }"
			:content="tipsContent" />
		<u-modal v-model="applyState" title="温馨提示" @confirm="loginConfirm" :content-style="{ 'line-height': '1.5' }"
			content="恭喜您成为新管理员！"></u-modal>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex';
	import config from '@/tools/config.js';
	export default {
		name: 'applyAdministrators',
		data() {
			return {
				tipsModal: false, // 小提示弹框显/隐
				tipsContent: '1. 点击下方【获取授权码】按钮；2. 联系现任管理员，索取授权码；3. 输入信息并点击提交按钮，验证成功后，重新登录，即可成为新管理员。',
				applyState: false, // 恭喜成为管理员弹框显/隐
				// 倒计时系列内容
				validCodeList: {
					disableValidCode: true, // 按钮是否可以点击
					validCodeText: '获取授权码', // 获取授权码
					validTimeText: '60秒', // 倒计时文案
					count: 60, // 倒计时秒数
					timer: null // 定时器
				},
				failTitle: '', // 失败弹框的标题
				failContent: '', // 失败弹框的提示语
				failModal: false, // 失败弹框的显/隐
				// 人脸识别相关
				faceInfo: {
					faceState: false, // 人脸识别（通过true，不通过false）
					sessionId: '', // 百度sessionId
					accessToken: '', // 百度accesstoken
					sessionCode: '', // 用户需要大声读出数字
					videoPath: '', // 上传视频后返回的临时视频路径
					videoBase64: '', // 视频base64
					imageBase64: '' // 图片base64
				},
				// 提交的参数
				params: {
					administratorsphone: '',
					name: '',
					idcard: '',
					code: ''
				}
			};
		},
		onLoad() {
			this.getAdminPhone(); // 获取当前管理员手机号
			this.tipsModal = true;
		},
		methods: {
			...mapMutations(['changeTabberIndex']),
			// 点击小提示----
			tipsClick() {
				this.tipsModal = true;
			},
			// 获取当前管理员手机号
			async getAdminPhone() {
				this.$refs.loading.openLoading('加载中···'); // 打开loading动画
				const data = await this.$http.post({
					url: '/sys/user/getManagerPhone'
				});
				if (data.code == 200) {
					this.params.administratorsphone = data.data;
				}
				this.$refs.loading.closeLoading(); // 关闭loading动画
			},
			// 点击进行人脸认证-----------------
			faceAuthenticationClick() {
				let that = this;
				if (!this.params.name) {
					this.$refs.uToast.show({
						title: '请输入姓名',
						type: 'error'
					});
					return;
				}
				if (!this.$check.IDCardCheck(this.params.idcard)) {
					this.$refs.uToast.show({
						title: '请输入正确的身份证号',
						type: 'error'
					});
					return;
				}
				uni.showModal({
					title: '温馨提示',
					content: '请您确定身份证号码和姓名是您本人且正确无误，否则将不能进行身份认证！',
					showCancel: true, // 是否显示取消按钮，默认为 true
					cancelText: '取消认证', // 取消按钮的文字
					confirmText: '开始认证', // 确认按钮的文字
					confirmColor: '#3178FF',
					cancelColor: '#606266',
					success: function(res) {
						if (res.confirm) {
							uni.request({
								url: 'https://aip.baidubce.com/oauth/2.0/token', //是真实的接口地址
								data: {
									grant_type: config.baidu_grant_type,
									client_id: config.baidu_client_id, //用你创建的应用的API Key
									client_secret: config.baidu_client_secret //用你创建的应用的Secret Key
								},
								header: {
									'Content-Type': 'application/json'
								},
								success(res) {
									that.faceInfo.accessToken = res.data.access_token;
									//获取活体认证的数字验证码
									uni.request({
										url: 'https://aip.baidubce.com/rest/2.0/face/v1/faceliveness/sessioncode?access_token=' +
											that.faceInfo.accessToken,
										method: 'POST',
										data: {
											min_code_length: 4,
											max_code_length: 4
										},
										header: {
											'Content-Type': 'application/x-www-form-urlencoded'
										},
										success(res) {
											if (res.data.err_no == 0) {
												that.faceInfo.sessionId = res.data.result
													.session_id;
												uni.showModal({
													title: '录制人脸视频警告',
													content: '人脸视频录制过程中，请大声的读出：' + res
														.data.result.code,
													confirmColor: '#3178FF',
													cancelColor: '#606266',
													confirmText: '确定',
													success: function(res) {
														if (res.confirm) {
															uni.chooseVideo({
																count: 1,
																sizeType: [
																	'compressed'
																],
																sourceType: [
																	'camera'
																],
																maxDuration: 10,
																camera: 'front',
																success(
																	res) {
																	// console.log('录制视频的地址返回的--------', res.tempFilePath);
																	that.faceInfo
																		.videoPath =
																		res
																		.tempFilePath;
																	that.$refs
																		.loading
																		.openLoading(
																			'活体认证中，请稍候'
																		); // 打开loading动画
																	uni.getFileSystemManager()
																		.readFile({
																			filePath: that
																				.faceInfo
																				.videoPath,
																			encoding: 'base64', //编码格式
																			success: res => {
																				//成功的回调
																				that.faceInfo
																					.videoBase64 =
																					res
																					.data;
																				that
																					.startVideoFaceProcess(); // 视频认证
																			},
																			fail: res => {
																				that.$refs
																					.loading
																					.closeLoading(); // 关闭loading动画
																				that.failTitle =
																					'认证失败'; // 失败的标题
																				that.failContent =
																					'人脸认证出现错误，请联系管理员！'; // 失败的提示语
																				that.failModal =
																					true; // 失败弹框的显/隐
																			}
																		});
																},
																fail(res) {
																	that.$refs
																		.loading
																		.closeLoading(); // 关闭loading动画
																	that.failTitle =
																		'认证失败'; // 失败的标题
																	that.failContent =
																		'请进行身份认证，否则无法注册！'; // 失败的提示语
																	that.failModal =
																		true; // 失败弹框的显/隐
																}
															});
														}
													}
												});
											} else if (res.data.err_no == 4 || res.data
												.err_no == 17 || res.data.err_no == 18 || res
												.data.err_no == 19) {
												that.$refs.loading
													.closeLoading(); // 关闭loading动画
												that.failTitle = '认证失败'; // 失败的标题
												that.failContent =
													'当前人脸识别人数过多，请稍后再试！'; // 失败的提示语
												that.failModal = true; // 失败弹框的显/隐
											} else {
												that.$refs.loading
													.closeLoading(); // 关闭loading动画
												that.failTitle = '认证失败'; // 失败的标题
												that.failContent =
													'当前人脸识别人数过多，请稍后再试！'; // 失败的提示语
												that.failModal = true; // 失败弹框的显/隐
											}
										}
									});
								},
								fail(res) {
									that.$refs.loading.closeLoading(); // 关闭loading动画
									that.failTitle = '认证失败'; // 失败的标题
									that.failContent = '人脸认证出现错误，请联系管理员！'; // 失败的提示语
									that.failModal = true; // 失败弹框的显/隐
								}
							});
						}
					}
				});
			},
			startVideoFaceProcess() {
				let that = this;
				let verifyVideo = {
					video_base64: that.faceInfo.videoBase64,
					session_id: that.faceInfo.sessionId,
					lip_identify: 'COMMON'
				};
				//获取活体认证的数字验证码
				uni.request({
					url: 'https://aip.baidubce.com/rest/2.0/face/v1/faceliveness/verify?access_token=' + that
						.faceInfo.accessToken,
					method: 'POST',
					data: verifyVideo,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success(res) {
						if (res.data.err_no == 0 && res.data.result.score >= 0.3 && res.data.result.code
							.similarity >= 0.75) {
							if (res.data.result.code.similarity < 0.75) {
								that.$refs.loading.closeLoading(); // 关闭loading动画
								that.failTitle = '认证失败'; // 失败的标题
								that.failContent = '请正确读出提示的4位数字号码！'; // 失败的提示语
								return;
							}
							that.faceInfo.imageBase64 = res.data.result.pic_list[3].pic;
							that.$refs.loading.openLoading('人脸识别中，请稍候'); // 打开loading动画
							//上传人脸检测
							uni.request({
								url: 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' +
									that.faceInfo.accessToken,
								method: 'POST',
								data: {
									image: that.faceInfo.imageBase64,
									image_type: 'BASE64',
									face_fields: 'age,beauty,expression,face_shape,gender,glasses,landmark,landmark150,race,quality,eye_status,emotion,face_type',
									liveness_control: 'NORMAL'
								},
								header: {
									'Content-Type': 'application/json'
								},
								success(res) {
									// console.log(res);
									if (
										res.data.error_msg == 'SUCCESS' &&
										res.data.result.face_num == 1 &&
										res.data.result.face_list[0].face_probability == 1 &&
										Math.abs(res.data.result.face_list[0].angle.pitch) < 20 &&
										Math.abs(res.data.result.face_list[0].angle.roll) < 20 &&
										Math.abs(res.data.result.face_list[0].angle.yaw) < 20 &&
										res.data.result.face_list[0].liveness.livemapscore > 0.393241
									) {
										var identityInfo = {
											name: that.params.name,
											idcard: that.params.idcard,
											image: 'data:image/png;base64,' + that.faceInfo.imageBase64
										};
										that.$refs.loading.openLoading('身份认证中，请稍候'); // 打开loading动画
										//公安系统接口认证
										that.$http
											.post({
												url: '/face/idcard',
												data: JSON.stringify(identityInfo)
											})
											.then(res => {
												if (res.code == 200) {
													if (res.data.isvalid) {
														//公安系统 认证成功！！！
														that.$refs.loading.openLoading(
															'人脸上传中，请稍候'); // 打开loading动画
														//上传人脸库
														wx.request({
															url: 'https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=' +
																that.faceInfo.accessToken,
															method: 'POST',
															data: {
																image: that.faceInfo
																	.imageBase64,
																image_type: 'BASE64',
																group_id: config
																	.baidu_group_id, //自己建的用户组id
																user_id: config
																	.baidu_userid_pre + that
																	.params.idcard //这里获取用户昵称
															},
															header: {
																'Content-Type': 'application/json'
															},
															success(res) {
																// console.log('身份认证返回的结果------', res);
																if (res.data.error_msg ==
																	'SUCCESS') {
																	that.$refs.loading
																		.closeLoading(); // 关闭loading动画
																	that.$refs.uToast.show({
																		title: '身份认证成功！',
																		type: 'suceess'
																	});
																	that.faceInfo.faceState =
																		true;
																} else {
																	if (res.data.error_code ==
																		'222210' || res.data
																		.error_code == '223105'
																	) {
																		that.$refs.loading
																			.openLoading(
																				'人脸更新中，请稍候'
																			); // 打开loading动画
																		// 比对公安人证信息
																		wx.request({
																			url: 'https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update?access_token=' +
																				that
																				.faceInfo
																				.accessToken,
																			method: 'POST',
																			data: {
																				image: that
																					.faceInfo
																					.imageBase64,
																				image_type: 'BASE64',
																				group_id: config
																					.baidu_group_id, //自己建的用户组id
																				user_id: config
																					.baidu_userid_pre +
																					that
																					.params
																					.idcard //这里获取用户昵称
																			},
																			header: {
																				'Content-Type': 'application/json'
																			},
																			success(
																				res) {
																				//做成功判断
																				that.$refs
																					.loading
																					.closeLoading(); // 关闭loading动画
																				if (res
																					.data
																					.error_msg ==
																					'SUCCESS'
																				) {
																					that.$refs
																						.uToast
																						.show({
																							title: '人脸更新成功！',
																							type: 'suceess'
																						});
																					that.faceInfo
																						.faceState =
																						true;
																				} else {
																					that.faceInfo
																						.faceState =
																						false;
																					that.$refs
																						.uToast
																						.show({
																							title: '人脸更新失败！' +
																								res
																								.data
																								.error_msg,
																							type: 'suceess'
																						});
																				}
																			}
																		});
																	} else {
																		that.$refs.loading
																			.closeLoading(); // 关闭loading动画
																		that.failTitle =
																			'认证失败'; // 失败的标题
																		that.failContent =
																			'认证失败！' + res
																			.data
																			.error_msg; // 失败的提示语
																		that.failModal =
																			true; // 失败弹框的显/隐
																	}
																}
															}
														});
													} else {
														that.faceInfo.faceState = false;
														that.$refs.loading
															.closeLoading(); // 关闭loading动画
														that.failTitle = '认证失败'; // 失败的标题
														that.failContent =
															'公安系统身份认证失败，请重新认证！'; // 失败的提示语
														that.failModal = true; // 失败弹框的显/隐
													}
												} else {
													if (res.data && res.data.length > 0) {
														that.faceInfo.faceState = false;
														that.$refs.loading
															.closeLoading(); // 关闭loading动画
														that.failTitle = '认证失败'; // 失败的标题
														that.failContent = '身份认证失败，请重新认证！'; // 失败的提示语
														that.failModal = true; // 失败弹框的显/隐
													} else {
														that.$refs.loading
															.closeLoading(); // 关闭loading动画
														that.failTitle = '认证失败'; // 失败的标题
														that.failContent = '身份认证认证异常！'; // 失败的提示语
														that.failModal = true; // 失败弹框的显/隐
													}
												}
											});
									} else {
										that.faceInfo.faceState = false;
										that.$refs.loading.closeLoading(); // 关闭loading动画
										that.failTitle = '认证失败'; // 失败的标题
										that.failContent = '照片不符合要求，请重拍！'; // 失败的提示语
										that.failModal = true; // 失败弹框的显/隐
									}
								},
								fail(res) {
									that.faceInfo.faceState = false;
									that.$refs.loading.closeLoading(); // 关闭loading动画
									that.failTitle = '认证失败'; // 失败的标题
									that.failContent = '身份认证出现错误，请联系管理员！'; // 失败的提示语
									that.failModal = true; // 失败弹框的显/隐
								}
							});
						} else if (res.data.err_no == 4 || res.data.err_no == 17 || res.data.err_no == 18 || res
							.data.err_no == 19) {
							that.$refs.loading.closeLoading(); // 关闭loading动画
							that.failTitle = '认证失败'; // 失败的标题
							that.failContent = '当前人脸识别人数过多，请稍后再试！'; // 失败的提示语
							that.failModal = true; // 失败弹框的显/隐
						} else {
							that.$refs.loading.closeLoading(); // 关闭loading动画
							that.failTitle = '认证失败'; // 失败的标题
							that.failContent = '活体认证失败! 请录制本人语音视频'; // 失败的提示语
							that.failModal = true; // 失败弹框的显/隐
						}
					}
				});
			},
			// 点击获取管理员授权码
			getValidCoded() {
				this.$refs.loading.openLoading('获取授权码···'); // 打开loading动画
				this.$http.get({
					url: `/sys/user/sendApplyManagerCode`
				}).then(res => {
					// console.log('获取授权码----', res);
					if (res.code == 200 && res.data) {
						this.$refs.uToast.show({
							title: '授权码发送成功，请尽快联系管理员获取授权码',
							type: 'success',
							duration: 3000
						});
						this.validCodeList.count = 60;
						this.validCodeList.disableValidCode = false;
						this.validCodeList.timer = setInterval(() => {
							if (this.validCodeList.count > 0 && this.validCodeList.count <= 60) {
								this.validCodeList.validTimeText = this.validCodeList.count + '秒';
								this.validCodeList.count--;
							} else {
								this.validCodeList.disableValidCode = true;
								this.validCodeList.validCodeText = '重新获取';
								this.validCodeList.validTimeText = '60秒';
								clearInterval(this.validCodeList.timer);
								this.validCodeList.timer = null;
							}
						}, 1000);
					} else {
						this.$refs.uToast.show({
							title: res.msg,
							type: 'error'
						});
					}
					this.$refs.loading.closeLoading(); // 关闭loading动画
				});
			},
			// 申请成为管理员----提交
			applyClick() {
				if (!this.params.name) {
					this.$refs.uToast.show({
						title: '请输入姓名',
						type: 'error'
					});
					return;
				}
				if (!this.$check.IDCardCheck(this.params.idcard)) {
					this.$refs.uToast.show({
						title: '请输入正确的身份证号',
						type: 'error'
					});
					return;
				}
				if (!this.faceInfo.faceState) {
					this.$refs.uToast.show({
						title: '请进行人脸认证',
						type: 'error'
					});
					return;
				}
				if (this.params.code == '') {
					this.$refs.uToast.show({
						title: '请输入授权码',
						type: 'error'
					});
					return;
				}
				this.$refs.loading.openLoading('申请中···'); // 打开loading动画
				delete this.params.administratorsphone;
				this.$http
					.post({
						url: '/sys/user/applyCompanyManager',
						data: this.params
					})
					.then(res => {
						// console.log('申请管理员返回的结果-----', res);
						this.$refs.loading.closeLoading(); // 关闭loading动画
						if (res.code == 200) {
							this.applyState = true;
						} else {
							this.$refs.uToast.show({
								title: res.msg,
								type: 'error'
							});
						}
					});
			},
			// 申请成功弹窗----确定操作
			loginConfirm() {
				this.changeTabberIndex(0);
				uni.clearStorageSync(); // 清空本地所有的缓存数据
				this.$pageJump.reLaunch('/pages/loginRegister/login/Login');
			}
		}
	};
</script>

<style lang="scss" scoped>
	.applyAdministrators {
		&-but {
			width: 90%;
			margin: 12% 5%;
		}

		.tips {
			position: absolute;
			right: 5%;
		}
	}
</style>